39. 组合总和
为保证权益,题目请参考 39. 组合总和(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
vector<vector<int>> ans;
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
vector<int> res;
dfs(0, target, res, candidates);
return ans;
}
void dfs(int i, int remain, vector<int> res, vector<int> &candidates)
{
if (i < candidates.size())
{
while (remain >= 0)
{
dfs(i + 1, remain, res, candidates);
res.push_back(candidates[i]);
remain -= candidates[i];
}
}
else
{
if (remain == 0)
{
ans.push_back(res);
}
}
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41